import axios from "axios"; // 引用axios
import config from "@/api/config";
import { ElMessage } from 'element-plus'
import router from '@/router'
const instance = axios.create({
  baseURL: config.baseUrl.dev,
  timeout: 60000,
});


//请求拦截
instance.interceptors.request.use(function (config) {
  // console.log(config)
  let token = sessionStorage.getItem("accessToken");
  if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.loginToken = token;
  }
  return config
}, function (error) {
  return Promise.reject(error)
});


//响应拦截
instance.interceptors.response.use(function (response) {
  // console.log(response)
  return response
}, function (error) {
  if(error.response.status == 401 || error.response.status == 402){
      ElMessage.error('登陆失败');
      router.push('/login')
  }
  console.log(error)
  return Promise.reject(error)
});



//post请求
export function post(url, data = {},config={}) {
  return new Promise((resolve, reject) => {
    instance.post(url, data,config).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
//get请求
export function get(url, params = {},config={}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      },config)
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}




